<template>
  <div id="app">
    <div id="map"></div>
    <Charts />
  </div>
</template>

<script>
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import cityPoly from '../static/cityPoly.json';
import point from '../static/cityLabel.json';
import HelloWorld from './components/HelloWorld';
import Charts from './components/charts';

// 不放到Vue是因为不需要对这些属性进行胁持，提高性能
let map = null;
// const svgStr = '<svg width="285" height="350" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M.725 20.775c0-10.99 8.91-19.9 19.9-19.9H194.75l89.55 89.55v238.8c0 10.99-8.91 19.9-19.9 19.9H20.625c-10.99 0-19.9-8.91-19.9-19.9V20.775z" fill="url(#a)"/><path fill-rule="evenodd" clip-rule="evenodd" d="M194.75.875v69.65c0 10.99 8.91 19.9 19.9 19.9h69.65L194.75.875z" fill="url(#b)"/><path d="M58.134 202.761c.372 11.233 9.828 18.005 24.034 18.005 14.909 0 24.035-7.35 24.035-18.996 0-9.044-5.492-14.123-18.088-16.643l-6.318-1.28c-7.02-1.404-9.911-3.675-9.911-7.35 0-4.378 4.13-7.269 10.282-7.269 6.277 0 10.696 3.056 11.11 8.136h11.769c-.207-10.944-8.961-18.212-22.879-18.212-13.255 0-22.754 7.227-22.754 18.129 0 8.879 5.823 14.578 17.716 16.932l6.277 1.238c7.475 1.529 10.283 3.759 10.283 7.682 0 4.377-4.543 7.598-11.191 7.598-6.773 0-11.81-2.973-12.595-7.97h-11.77zm86.31 17.014l20.028-59.59h-13.586l-13.628 46.747h-.289l-13.628-46.747h-13.958l20.029 59.59h15.032zm78.587-25.026v-6.731h-25.109v9.086h12.967l-.041.949c-.248 7.392-5.905 12.389-14.041 12.389-9.911 0-16.188-7.887-16.188-20.813 0-12.678 5.906-20.153 15.734-20.153 6.731 0 11.811 3.717 13.628 9.952h12.513c-1.776-12.058-12.266-20.276-26.182-20.276-17.51 0-28.412 11.563-28.412 30.642 0 19.368 10.902 30.972 28.701 30.972 16.601 0 26.43-9.787 26.43-26.017z" fill="#FF8C02"/><defs><linearGradient id="a" x1=".725" y1=".875" x2=".725" y2="349.125" gradientUnits="userSpaceOnUse"><stop stop-color="#FFDFB8"/><stop offset="1" stop-color="#FFCA8A"/></linearGradient><linearGradient id="b" x1="194.75" y1=".875" x2="194.75" y2="90.425" gradientUnits="userSpaceOnUse"><stop stop-color="#FFCC8F"/><stop offset="1" stop-color="#FFBB69"/></linearGradient></defs></svg>'
const layers = {
  cityPoly: null,
  points: null,
};

export default {
  name: 'App',
  components: {
    HelloWorld,
    Charts,
  },
  mounted() {
    this.initMap();
    this.addCityOutline();
    this.addPoints();
  },
  methods: {
    initMap() {
      map = L.map('map')
        // 这里取兰州作为初始视点
        .setView([103.63972377952888, 36.35516785641147].reverse(), 2);

      // 使用mapbox瓦片
      L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
        maxZoom: 18,
        id: 'mapbox/streets-v11',
        tileSize: 512,
        zoomOffset: -1,
        accessToken: 'pk.eyJ1IjoiaHVhbmdodWF5ZSIsImEiOiJjaXE3cDAzYjkwMDJqaTBtMjgyeGU5OTgzIn0.6anjSnTDwPiIXV6f7kyRag',
      }).addTo(map);
    },
    toPoint(data, bound) {
      return `${data[0] - bound.lng} ${data[1] - bound.lat}`;
    },
    // 添加城市描边, 数据直接就是geoJSON，可以直接使用api添加
    addCityOutline() {
      const coords = [];
      layers.cityPoly = L.geoJSON(cityPoly, /* 描边和填充颜色可以写在options里面，这里省略 */{
        onEachFeature(data, layer) {
          coords.push({
            coords: data.geometry.coordinates[0],
            bound: layer.getBounds(),
          });
        },
      })
        .addTo(map);

      // 目前取第一个银川市做裁剪示例，多个可以用同样的办法
      L.svgOverlay(this.buildSvg(coords[0]), coords[0].bound, {
        className: 'image-clip',
      }).addTo(map);
      // const svg = this.buildSvg(coords[0]);
      // document.body.appendChild(svg);
      // L.imageOverlay('/static/player-bg@2x.png ', coords[0].bound, {
      //   className: 'image-clip',
      // }).addTo(map);
    },
    buildSvg(data) {
      const northEast = map.project(data.bound.getNorthEast(), 0);
      const southWest = map.project(data.bound.getSouthWest(), 0);

      const x = southWest.x;
      const y = northEast.y;
      const yScale = southWest.y - northEast.y;
      const xScale = northEast.x - southWest.x;

      const svgElement = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
      svgElement.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
      svgElement.setAttribute('viewBox', `0 0 ${xScale} ${yScale}`);
      svgElement.setAttribute('preserveAspectRatio', 'none meet');

      svgElement.innerHTML = `<image preserveAspectRatio="none meet" xlink:href="/static/player-bg@2x.png" x="0" y="0" width="${xScale}" height="${yScale}" clip-path="url(#clip)" fill="red" />` +
        `<clipPath id="clip"><path fill="black" d="${data.coords
          .map((item, index) => {
            const projected = map.project(item.reverse(), 0);
            return `${index === 0 ? 'M' : 'L'} ${projected.x - x} ${projected.y - y}`;
          })}z" /></clipPath>`;

      return svgElement;
    },
    // 添加站点
    addPoints() {
      layers.points = L.geoJSON(point, {
        // 添加一个小圆点
        pointToLayer(item, latlng) {
          const { properties } = item;
          return L.circleMarker(latlng, {
            radius: 10,
            color: (properties.CODE / 100) % 2 === 0 ? 'green' : 'red',
          })
            // 弹出这些简单使用tooltip，需要定制可以传入html字符串和传入className定制css属性
            .bindTooltip(`${properties.NAME}-${properties.CODE}`, {
              direction: 'right',
              offset: [10, 0],
            });
        },
      }).addTo(map);
    },
  },
};
</script>

<style>
  html, body, #app {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
  }

  #map {
    width: 100%;
    height: calc(100% - 400px);
  }

  .image-clip {
    width: 100%;
    height: 100%;
  }
</style>
